package com.hruiworks.campusgroup.quartz.listener;

import org.quartz.*;

/**
 * 全局工作监听器
 * @author jiushui
 * 每一个工作都应该被注册于全局工作监听，用于处理所有的任务
 */
public class GlobalJobListener implements JobListener {
    @Override
    public String getName() {
        return "global_job_listener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {

    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {

    }

    /**
     * 任务执行后操作
     * @param context 上下文
     * @param jobException 任务异常
     */
    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        if (jobException == null) {
            Scheduler scheduler = context.getScheduler();
            try {
                // 删除触发器
                scheduler.unscheduleJob(context.getTrigger().getKey());
                // 删除任务
                scheduler.deleteJob(context.getJobDetail().getKey());
            } catch (SchedulerException e) {
                throw new RuntimeException(e);
            }

        } else {
            System.err.println("Job execution failed: " + jobException.getMessage());
        }
    }
}
